<template>
  <div class="sse-demo">
    <h2>SSE 实时消息展示</h2>
    <div v-if="messages.length === 0">等待消息...</div>
    <ul>
      <li v-for="(msg, index) in messages" :key="index">
        {{ msg }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      messages: [],
      token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiQ3BCN1ZyZjFrV21ERmxLZHlTNG96dnpUeW5xQjVPMzEiLCJ0ZW5hbnQiOjEsInVzZXJJZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImRlcHRJZCI6MSwiZGVwdENvZGUiOiJBMDEifQ.HgXa44FafXddegf6ydqoavXpxUtMsv9ZFpFO0dZTjeY', // 替换为你的认证 token
      sseUrl: 'http://localhost:8080/admin-api/sse', // 替换为你的后端 SSE 地址
    };
  },
  mounted() {
    this.connectSSE();
  },
  methods: {
    connectSSE() {
      // 拼接 token 到 URL 查询参数中传递
      const urlWithToken = `${this.sseUrl}?ks-sample-token=${this.token}`;
      const eventSource = new EventSource(urlWithToken);

      eventSource.addEventListener('message', (event) => {
        this.messages.push(event.data);
      });

      eventSource.addEventListener('error', (err) => {
        console.error('SSE 连接异常:', err);
        this.messages.push('连接异常，请检查服务或 token');
      });

      eventSource.addEventListener('open', () => {
        console.log('SSE 连接已建立');
      });
    },
  },
};
</script>

<style scoped>
.sse-demo {
  padding: 20px;
  border: 1px solid #ddd;
  max-width: 600px;
  margin: 20px auto;
}
ul {
  list-style-type: none;
  padding-left: 0;
}
li {
  background-color: #f9f9f9;
  color: red;
  margin: 5px 0;
  padding: 8px;
  border-radius: 4px;
}
</style>
